package com.yeyaomai.dksns.flowis.quartz;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.mapreduce.GroupByResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Order;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import com.yeyaomai.dksns.flowis.dao.DetailDao;
import com.yeyaomai.dksns.flowis.domain.flowisdetail.FlowisStatDetailDTO;
import com.yeyaomai.dksns.flowis.util.CollectionNames;
import com.yeyaomai.dksns.flowis.util.VelocityToolDateUtils;

/**
 * 
 * 定时分析mongo中数据，计算停留时间和判断离开页面
 * 
 * @author zhaocm
 * 
 */
public class StoptimeAndLeaveExecuto {

	@Resource
	private DetailDao detailDao;

	public void stoptimeAndLeaveTiming() throws ParseException {

		final Logger logger = Logger.getLogger("quartz");
		
		String st = VelocityToolDateUtils.getHour(-1);
		String et = VelocityToolDateUtils.getHour(0);
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		GroupByResults<FlowisStatDetailDTO> cookies = groupCookie(st, et);
		if (cookies.getKeys() != 0) {
			for (FlowisStatDetailDTO cookie : cookies) {
				Query query = new Query(Criteria.where("access_date").gte(st)
						.lt(et).and(CollectionNames.COOKIEID).is(cookie.getCookieId()));
				query.sort().on("access_date", Order.ASCENDING);
				List<FlowisStatDetailDTO> flows = detailDao.findList(query);
				String lastTime = "";
				ObjectId Id = new ObjectId();
				if (flows.size() > 1) {
					for (FlowisStatDetailDTO flow : flows) {
						if (lastTime != "") {
							long stoptime = sd.parse(flow.getAccess_date()).getTime() - sd.parse(lastTime).getTime();
							if (stoptime != 0) {
								Update update = Update.update("stoptime",stoptime / 100);
								if (stoptime > 18000 || flow.getReferer().equals("")) {
									detailDao.update(Criteria.where("_id").is(Id),Update.update("close", 1));
								}
								if (stoptime <= 18000) {
									detailDao.update(Criteria.where("_id").is(Id),update);
								}
							}
						}
						lastTime = flow.getAccess_date();
						Id = flow.getId();
					}
				} else if (flows.size() == 1) {
					detailDao.update(Criteria.where("_id").is(Id),Update.update("close", 1));
				}
			}
		}
		logger.info("停留时间计算、判断离开页面： 执行时间：" + sd.format(new Date()) + " 处理独立访客数：" + cookies.getKeys());
	}

	// 根据cookie分组 排序
	private GroupByResults<FlowisStatDetailDTO> groupCookie(String st, String et) {

		String mapFunction = "{ req_source: 0}";
		String reduceFunction = "function(key,values) {values.req_source+=1}";
		Criteria criteria = Criteria.where("cookieId").ne("null")
				.and("access_date").gte(st).lt(et);
		return detailDao.group(criteria, CollectionNames.COOKIEID, mapFunction,
				reduceFunction, FlowisStatDetailDTO.class);
	}
}
